package cn.minimelon.solon.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class MavenCleanUtil {

    public static void main(String[] args) {
        clean("D:\\02Envs\\repository");
    }
    
    public static void clean(String dir) {
        cleanDir(dir);
    }

    private static void cleanDir(String dir) {
        File[] fileList = FileUtil.ls(dir);
        if (isVersionList(fileList)) {
            if (fileList.length > 1) {
                try {
                    List<File> sortList = Arrays.stream(fileList).sorted(Comparator.comparing(a -> toInt(a.getName()))).collect(Collectors.toList());
                    System.out.println("clean dir: " + dir);
                    for (int i = 0; i < sortList.size() - 1; i++) {
                        System.out.println("delete: " + sortList.get(i).getName());
                        FileUtil.del(sortList.get(i));
                    }
                    for (int i = sortList.size() - 1; i < sortList.size(); i++) {
                        System.out.println("remain: " + sortList.get(i).getName());
                    }
                } catch(Exception ex) {
                    System.out.println("clean dir: " + dir);
                }
            }
        } else {
            if (fileList.length > 0) {
                for (File file : fileList) {
                    if (file.isDirectory()) {
                        cleanDir(file.getAbsolutePath());
                    }
                }
            }
        }
    }

    private static boolean isVersionList(File[] list) {
        if (list.length > 0) {
            String path = list[0].getAbsolutePath() + "\\_remote.repositories";
            return FileUtil.isFile(path);
        }
        return false;
    }

    private static Integer toInt(String name) {
        int[] arrInt = {1, 100, 10000, 1000000};
        String[] arr = name.split("\\.");
        int num = 0;
        for (int i = 0; i < arr.length; i++) {
            if (NumberUtil.isInteger(arr[i])) {
                num = num  + arrInt[3 - i] * Integer.parseInt(arr[i]);
            }
        }
        return num;
    }
}
